package cn.com.csg.smartenergy.modules.biz.task.service;


import cn.com.csg.smartenergy.common.Constant;
import cn.com.csg.smartenergy.common.DateUtils;
import cn.com.csg.smartenergy.modules.biz.energy.service.EnergyIotDeviceService;
import cn.com.csg.smartenergy.modules.biz.entity.IotDeviceEntity;
import cn.com.csg.smartenergy.modules.biz.task.core.CronTaskRegistrar;
import cn.com.csg.smartenergy.modules.biz.task.core.SchedulingRunnable;
import cn.com.csg.smartenergy.modules.biz.task.entity.TaskEntity;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TaskService {
    @Autowired
    CronTaskRegistrar cronTaskRegistrar;
    @Autowired
    private EnergyIotDeviceService energyIotDeviceService;

    private Map<String,HashMap<String,Float>> SOC = new ConcurrentHashMap<>();


    /**
     * 上下线，心跳定时任务启动删除
     * @param taskEntity
     * @throws InterruptedException
     */
    public void taskStartOrRemove(TaskEntity taskEntity) throws Exception {
        int action = taskEntity.getAction();
        String beanName = "sendTask";
        String methodName = "onLine";
        IotDeviceEntity iotDeviceEntity = taskEntity.getIotDeviceEntity();
        String manufacturerId = iotDeviceEntity.getManufacturerId();
        String manufacturerName = iotDeviceEntity.getManufacturerName();
        String deviceType = iotDeviceEntity.getDeviceType();
        String model = iotDeviceEntity.getModel();
        String nodeId = iotDeviceEntity.getNodeId();
        String protocolType = iotDeviceEntity.getProtocolType();
        String jobId = beanName + Constant.UNDER_LINE
                + methodName + Constant.UNDER_LINE
                + manufacturerId + Constant.UNDER_LINE
                + nodeId+Constant.UNDER_LINE
                + protocolType;
        if (action == 1) {//start
            String cron = taskEntity.getCron();
            if (StringUtils.isEmpty(cron)) {cron = "0/60 * * * * ?";}
            String message = "";
            //            message="{\n" +
//                    "    \"body\":{\n" +
//                    "        \"state\":\"online\",\n" +
//                    "        \"event-time\":\"2022-05-10 04:01:30\"\n" +
//                    "    },\n" +
//                    "    \"token\":\"4d4a36\",\n" +
//                    "    \"timestamp\":\"2022-05-10 04:01:30\"\n" +
//                    "}";

            HashMap data = new HashMap<String, Object>();
            String date = DateUtils.format(new Date(System.currentTimeMillis()), DateUtils.DATE_TIME_PATTERN);
            data.put(Constant.MSG_TIMESTAMP, date);
            //TODO:TOKEN??
            data.put(Constant.MSG_TOKEN, "9c0ca881-eac8-463e-8989-db0059fe3ded");
            HashMap body = new HashMap<String, Object>();
            body.put(Constant.STATE, Constant.ONLINE);
            body.put(Constant.EVENT_TIME,date);
            data.put(Constant.MSG_BODY, body);
            message = JSON.toJSONString(data);
            SchedulingRunnable task = new SchedulingRunnable(beanName, methodName, manufacturerId, manufacturerName, deviceType, model, nodeId,protocolType, message);
            cronTaskRegistrar.addCronTask(jobId,task, cron);
        } else if (action == 0) {//remove
            cronTaskRegistrar.removeCronTask(jobId);
        }
    }


    /**
     * 模拟数据发送定时任务启动删除
     * @param taskEntity
     * @throws InterruptedException
     */
    public void sendMessages(TaskEntity taskEntity) throws Exception {
        String ds = taskEntity.getDs();
        int action = taskEntity.getAction();
        String beanName = "sendTask";
        String methodName = "sendMessage";
        IotDeviceEntity iotDeviceEntity = taskEntity.getIotDeviceEntity();
        String manufacturerId = iotDeviceEntity.getManufacturerId();
        String manufacturerName = iotDeviceEntity.getManufacturerName();
        String deviceType = iotDeviceEntity.getDeviceType();
        String model = iotDeviceEntity.getModel();
        String nodeId = iotDeviceEntity.getNodeId();
        String protocolType = iotDeviceEntity.getProtocolType();
        String jobId =beanName + Constant.UNDER_LINE
                + methodName+ Constant.UNDER_LINE
                + manufacturerId + Constant.UNDER_LINE
                + nodeId + Constant.UNDER_LINE
                +protocolType;
        if (action == 1) {//start
            IotDeviceEntity byId = new IotDeviceEntity();
            if("energy".equals(ds)){
                byId = energyIotDeviceService.getById(iotDeviceEntity.getId());
            }else{
//                byId = deviceService.getById(iotDeviceEntity.getId());
            }
            String status = byId.getStatus();
            if (!StringUtils.isEmpty(status)&&status.toUpperCase().equals(Constant.ONLINE)) {
                String cron = taskEntity.getCron();
                if (StringUtils.isEmpty(cron)) {cron = "0/5 * * * * ?";}
                String serviceId = taskEntity.getServiceId();
                String message = taskEntity.getMessage();
//            HashMap data = new HashMap<String, Object>();
////            //TODO:TOKEN??
//            String date = DateUtils.format(new Date(), DateUtils.TIME_FORMAT_MQTT);
//            data.put("timestamp", date);
//            data.put("token", "9c0ca881-eac8-463e-8989-db0059fe3ded");
//            Map body = getMessageData(message);
////            body.put("state", "online");
////            body.put("event-time",date);
//            data.put("body", body);
//            message = JSON.toJSONString(data);
                SchedulingRunnable task = new SchedulingRunnable(beanName, methodName,serviceId, manufacturerId, manufacturerName, deviceType, model, nodeId, message,jobId,SOC);
                cronTaskRegistrar.addCronTask(jobId,task, cron);
            } else {
                throw new Exception("设备不在线，无法发送消息");
            }
        } else if (action == 0) {//remove
            cronTaskRegistrar.removeCronTask(jobId);
            SOC.remove(jobId);
        }
    }



}
